package com.sctvcloud.bazhong.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.application.Constances;
import com.sctvcloud.bazhong.base.BaseDetailActivity;
import com.sctvcloud.bazhong.beans.FOrganDetail;
import com.sctvcloud.bazhong.beans.FScribeState;
import com.sctvcloud.bazhong.beans.FUsers;
import com.sctvcloud.bazhong.beans.GovDetailBean;
import com.sctvcloud.bazhong.beans.GovItemBean;
import com.sctvcloud.bazhong.beans.HomeListItem;
import com.sctvcloud.bazhong.beans.NewsItem;
import com.sctvcloud.bazhong.http.AbsNetCallBack;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.http.ParamsEditor;
import com.sctvcloud.bazhong.ui.adapter.GovAdapter;
import com.sctvcloud.bazhong.ui.util.IListShowData;
import com.sctvcloud.bazhong.ui.utils.GlideCircleTransform;
import com.sctvcloud.bazhong.ui.utils.GlideUtil;
import com.sctvcloud.bazhong.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 评论详情(爆料的评论)
 */
public class GovDetailActivity extends BaseDetailActivity  implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView{


    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.item_city_state_channel_icon)
    protected CustomEXImageView icon;
    @BindView(R.id.item_city_state_channel_name)
    protected CustomFontTextView name;
    @BindView(R.id.item_city_state_channel_status)
    protected CustomFontTextView status;
    @BindView(R.id.title_top_title)
    protected CustomFontTextView title_top_title;

    @BindView(R.id.gov_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.gov_list)
    protected RecyclerView gov_list;
    private GovItemBean item;
    private int mPageNo = 0;
    private int mPageAll = 0;
    private final static int pageSize = 10;
    private boolean mIsLoading = false;
    private GovAdapter mAdapter;
    private boolean isSubscribe;
    private int types; //type 1 订阅 2取消订阅
    public static final int REQUEST_CODE_LOGIN = 101;
    GovDetailBean govDetail;

    private List<IListShowData> GovList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView(){

        item = (GovItemBean) getIntent().getSerializableExtra(EX_DATA);
        title_top_title.setVisibility(View.VISIBLE);
        title_top_title.setText(item.getInstitutionName());

        if(null!=item){
            isSubscribe = item.isSubscibe();
            initTop();
        }
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        gov_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        gov_list.setItemAnimator(new DefaultItemAnimator());
//        rebllion_list.addItemDecoration(new RBaseItemDecoration(2));
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();

    }


    private void initTop(){
        GlideUtil.getGlid(this, item.getInstitutionImage()).error(R.mipmap.icon_circle_avatar)
                .placeholder(R.mipmap.icon_circle_avatar).transform(new GlideCircleTransform(this))
                .into(icon);
        status.setBackgroundResource(item.isSubscibe() ? R.drawable.ucrop_bg_cv_red : R.drawable.bg_look_back);
        status.setText(item.isSubscibe() ? getString(R.string.city_state_subscribe) : getString(R.string.city_state_no_subscribe));
        status.setTextColor(item.isSubscibe() ? getResources().getColor(R.color.white) : getResources().getColor(R.color.blue_main));
        name.setText(item.getInstitutionName());
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_gov_detail);
        butterUnbinder = ButterKnife.bind(this);
    }

    @OnClick({R.id.title_top_back,R.id.item_city_state_channel_status,R.id.title_top_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                finish();
                break;
            case R.id.item_city_state_channel_status:
                getSubscribeStateChange();
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", "政务"));
                pairs.add(new Pair<>("位置", "专题名称"));
                if (isSubscribe) {
                    pairs.add(new Pair<>("行为类型", "取消订阅"));
                } else {
                    pairs.add(new Pair<>("行为类型", "点击订阅"));
                }
                GridsumWebDissector.getInstance().trackEvent(GovDetailActivity.this, "", item.getInstitutionName(), "", 200, pairs);
                break;
            case R.id.title_top_share:
                if (changetoFOrganDetail(govDetail) != null && !TextUtils.isEmpty(changetoFOrganDetail(govDetail).getSharedUrl())) {
                    this.setNewsId(item.getInstitutionId());
                    showShareFragment(changetoFOrganDetail(govDetail), new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {
                            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                            pairs.add(new Pair<>("页面", "首页"));
                            pairs.add(new Pair<>("栏目", "政务"));
                            pairs.add(new Pair<>("位置", "分享"));
                            pairs.add(pair);
                            GridsumWebDissector.getInstance().trackEvent(GovDetailActivity.this, "", item.getInstitutionName(), "", 200, pairs);
                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }

                break;

            default:
                break;
        }
    }


    private FOrganDetail changetoFOrganDetail(GovDetailBean bean){
        FOrganDetail item = new FOrganDetail();
        item.setDynamicList(bean.getDataList());
        item.setInstitutionId(bean.getInstitutionId());
        item.setInstitutionName(bean.getInstitutionName());
        item.setSharedUrl(bean.getShareUrl());
        item.setInstitutionImage(bean.getInstitutionImage());
        return  item;
    }


    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mPageNo = 0;
        mIsLoading = true;
        GovList.clear();
        getData();
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(gov_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(gov_list, 1);
    }


    private void getData() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("page", mPageNo);
        param.put("size", pageSize);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("nodeId", item.getInstitutionId());

        NetUtils.getNetAdapter().getOrgInfos(getOwnerName(), param, new AbsNetCallBack<GovDetailBean>(GovDetailBean.class) {
            @Override
            public void onSuc(GovDetailBean fRebellions) {
                govDetail = fRebellions;
                if (mPageAll == 0) {
                    mPageAll = fRebellions.getPageAll();
                }

                initData(fRebellions);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(R.string.loading_no_data);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        refreshLayout.setLoadMoreEnabled(mPageNo >= mPageAll ? false : true);
    }

    private void initData(GovDetailBean fRebellions) {

        if (ListUtils.isListValued(fRebellions.getRollImg())) {
            HomeListItem hb = new HomeListItem();
            hb.setNewsItemList(fRebellions.getRollImg());
            hb.setViewType(GovAdapter.VIEWTYPE_BANNER);
            GovList.add(hb);
        }

        if (ListUtils.isListValued(fRebellions.getDataList())) {
            GovList.addAll(fRebellions.getDataList());
        }

        if (mAdapter == null) {
            mAdapter = new GovAdapter(this, GovList);
            mAdapter.setItemInternalClick(itemClick);
            gov_list.setAdapter(mAdapter);
            mAdapter.setActivity(this);
        }else{
            mAdapter.setData(GovList);
        }
        mPageNo++;
    }


    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
//                case R.id.tv_anchor_comment:
//                    ArrayList<Pair<String, String>> pairs = new ArrayList<>();
//                    pairs.add(new Pair<>("页面", "首页"));
//                    pairs.add(new Pair<>("栏目", "市州"));
//                    pairs.add(new Pair<>("位置", "专题名称"));
//                    ArrayList<Pair<String, String>> pairsMap = new ArrayList<>();
//                    pairsMap.addAll(pairs);
//                    pairsMap.add(new Pair<>("行为类型", "点击"));
//                    GridsumWebDissector.getInstance().trackEvent(activity, "", titleName, "", 200, pairsMap);
//                    HashMap<String, String> map = new HashMap<>();
//                    for (Pair<String, String> p : pairs) {
//                        map.put(p.first, p.second);
//                    }
//                    SkipUtil.skipWithNewsItem(context, newsItem, map);
//                    break;

            }
        }
    };


    /**
     * 市州媒体订阅或取消订阅请求
     */
    private void getSubscribeStateChange() {

        if (UserManager.getInstance().isLogin()) {
            FUsers user = UserManager.getInstance().getUser();
            if (isSubscribe) {
                types = 2;
            } else {
                types = 1;
            }

            ParamsEditor pe = new ParamsEditor();
            pe.put("institutionId", item.getInstitutionId());
            pe.put("type", types); //1订阅 2 取消订阅
            pe.put("userId", user.getUserId());
            NetUtils.getNetAdapter().getSubscribeState(getOwnerName(), pe.getEncryptedParams(user.getToken())
                    , new AbsNetCallBack<FScribeState>(FScribeState.class) {
                        @Override
                        public void onSuc(FScribeState scribeState) {
                            isSubscribe = !isSubscribe;
                            initSubscribeStateView(isSubscribe);

                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
                            JLog.e("====error=" + errorMsg);
                            toast(errorMsg);
                        }
                    });

        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_CODE_LOGIN);
        }

    }



    /**
     * 显示订阅或未订阅
     */
    private void initSubscribeStateView(boolean isSubscribe) {
        status.setText(isSubscribe ? getString(R.string.city_state_subscribe) : getString(R.string.city_state_no_subscribe));
        status.setTextColor(isSubscribe ? getResources().getColor(R.color.white) : getResources().getColor(R.color.blue_main));
        status.setBackgroundResource(isSubscribe ? R.drawable.ucrop_bg_cv_red : R.drawable.bg_look_back);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOGIN) {
            onRefresh();
        }
    }


    @Override
    public void onBackPressed() {
        setResultes();
        super.onBackPressed();
    }

    private void setResultes() {
        Intent intent = getIntent();
        setResult(RESULT_OK, intent);
        finish();
    }
}
